package com.pearl.study05.demo.validation;

import cn.hutool.core.util.StrUtil;
import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseListener;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;
import org.camunda.bpm.engine.impl.util.xml.Element;
import org.camunda.bpm.model.bpmn.instance.EndEvent;
import org.camunda.bpm.model.bpmn.instance.Process;
import org.camunda.bpm.model.bpmn.instance.SubProcess;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;
import org.camunda.bpm.model.xml.validation.ModelElementValidator;
import org.camunda.bpm.model.xml.validation.ValidationResultCollector;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author TD
 * @version 1.0
 * @date 2024/1/15
 */
public class ProcessValidator implements ModelElementValidator<Process> {
    @Override
    public Class<Process> getElementType() {
        return Process.class;
    }

    @Override
    public void validate(Process parentElement, ValidationResultCollector validationResultCollector) {
        validateHasEndEvent(parentElement, validationResultCollector, parentElement.getName(), "流程模型【{}】必须包含一个结束事件");
        //validateUserTask(parentElement, validationResultCollector, parentElement.getName(), "用户任务【{}】处理人不能为空");
        // 子流程
        Collection<SubProcess> subProcesses = parentElement.getChildElementsByType(SubProcess.class);
        if (!subProcesses.isEmpty()) {
            for (SubProcess subProcess : subProcesses) {
                validateHasEndEvent(subProcess, validationResultCollector, subProcess.getName(), "子流程【{}】必须包含一个结束事件");
                //validateUserTask(parentElement, validationResultCollector, parentElement.getName(), "子流程用户任务【{}】处理人不能为空");
            }
        }
    }

    private void validateHasEndEvent(ModelElementInstance element, ValidationResultCollector validationResultCollector, String name, String msg) {
        Collection<EndEvent> endEvents = element.getChildElementsByType(EndEvent.class);
        int endEvent = endEvents.size();
        if (endEvent == 0) {
            // 添加错误信息到结果收集器中
            validationResultCollector.addError(500, StrUtil.format(msg, name));
        }
    }

    private void validateUserTask(ModelElementInstance element, ValidationResultCollector validationResultCollector, String name, String msg) {
        Collection<UserTask> userTasks = element.getChildElementsByType(UserTask.class);
        if (!userTasks.isEmpty()){
            for (UserTask userTask : userTasks) {
                // 校验是否设置审批人
                String camundaAssignee = userTask.getCamundaAssignee();
                if (StrUtil.isEmpty(camundaAssignee)) {
                    validationResultCollector.addError(500,  StrUtil.format(msg, name));
                }
            }
        }
    }
}
